package com.aaron.kjviewutils;

import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aaron.kjviewutils.retrofit.service.WeatherService;
import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends BaseActivity implements PullLoadMoreRecyclerView.PullLoadMoreListener {

    @Bind(R.id.pullLoadMoreRecyclerView)
    PullLoadMoreRecyclerView pullLoadMoreRecyclerView;
    @Bind(R.id.mainAppbar)
    AppBarLayout mainAppbar;
    @Bind(R.id.mainToolBar)
    Toolbar mainToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;

    private List<MainBean.MainSub> datas;
    private MainRecyclerViewAdapter adapter;
    private RecyclerView mRecyclerView;
    private ItemTouchHelper mItemTouchHelper;
    private Call<MainBean> mainCall;
    private WeatherService weatherService;
    private String provde;
    private String city;
    /*private SlidingMenu menu;
    private View slidingMenuView;
    private ImageView userLogo;
    private TextView userTag;
    private RelativeLayout setting01;
    private RelativeLayout setting02;
    private RelativeLayout setting03;
    private ImageView settingIcon01;
    private ImageView settingIcon02;
    private ImageView settingIcon03;*/

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        /*if(null!=menu)
        {
            menu.showMenu(true);
        }*/
        closeSelf(MainActivity.this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initTitle();
        String[] citys = obtainCitys();
        if(!TextUtils.isEmpty(citys[0])&&!TextUtils.isEmpty(citys[1]))
        {
            provde = citys[0];
            city = citys[1];
        }
        else
        {
            provde = "浙江";
            city = "杭州";
        }
        if(null!=retrofit)
        {
            weatherService = retrofit.create(WeatherService.class);
            mainCall = weatherService.obtainWeather(provde, city);
            initRecyclerView();
            initTouch();
        }
        else
        {
            //retrofit组件初始化失败
            Toast.makeText(MainActivity.this, "retrofit组件初始化失败", Toast.LENGTH_SHORT).show();
        }
    }

    /*private void initSlidingMenu()
    {
        // configure the SlidingMenu
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);
        // 设置触摸屏幕的模式
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
        menu.setShadowWidthRes(R.dimen.shadow_width);
        menu.setShadowDrawable(R.drawable.shadow);

        // 设置滑动菜单视图的宽度
        menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        // 设置渐入渐出效果的值
        menu.setFadeDegree(0.5f);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //为侧滑菜单设置布局
        slidingMenuView = View.inflate(MainActivity.this, R.layout.layout_sliding, null);
        userLogo = (ImageView) slidingMenuView.findViewById(R.id.userLogo);
        userTag = (TextView) slidingMenuView.findViewById(R.id.userTag);
        setting01 = (RelativeLayout) slidingMenuView.findViewById(R.id.setting01);
        setting02 = (RelativeLayout) slidingMenuView.findViewById(R.id.setting02);
        setting03 = (RelativeLayout) slidingMenuView.findViewById(R.id.setting03);
        settingIcon01 = (ImageView) slidingMenuView.findViewById(R.id.settingIcon01);
        settingIcon02 = (ImageView) slidingMenuView.findViewById(R.id.settingIcon02);
        settingIcon03 = (ImageView) slidingMenuView.findViewById(R.id.settingIcon03);
        menu.setMenu(slidingMenuView);
        mHandler.postDelayed(runnableLoadMenu, 1000);
        setting01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(MainActivity.this, MobDetailActivity.class, null);
            }
        });

        setting02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showActivity(MainActivity.this, SettingActivity.class, null);
            }
        });

        setting02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }*/

    /*Runnable runnableLoadMenu = new Runnable() {
        @Override
        public void run() {
            Glide.with(MainActivity.this).load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487072926350&di=873d4c187b6820cae24019ff8e5b69d8&imgtype=0&src=http%3A%2F%2Fimages.rednet.cn%2Farticleimage%2F2006%2F07%2F24%2F101724409.jpg").transform(new GlideCircleTransform(MainActivity.this)).dontAnimate().placeholder(R.mipmap.ic_launcher).into(userLogo);
            userTag.setText("小Y");
            Glide.with(MainActivity.this).load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487074487176&di=6ee1ab8986995bcf2f9300f2edbcd534&imgtype=0&src=http%3A%2F%2Fscimg.jb51.net%2Fallimg%2F160316%2F77-160316144F60-L.jpg").animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(settingIcon01);
            Glide.with(MainActivity.this).load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487074556581&di=47217d3e5bba675e86f2632d6994d98e&imgtype=0&src=http%3A%2F%2Ff.hiphotos.baidu.com%2Fexp%2Fw%3D480%2Fsign%3Db784207419178a82ce3c7ea8c602737f%2F10dfa9ec8a1363275772188b968fa0ec09fac7ef.jpg").animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(settingIcon02);
            Glide.with(MainActivity.this).load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487074585677&di=42888d3aaa2504cdda2668c76718a5cc&imgtype=0&src=http%3A%2F%2Fimgs.ebrun.com%2Fresources%2F2015_03%2F2015_03_16%2F20150316_1426477906046.jpg").animate(android.R.anim.slide_in_left).placeholder(R.mipmap.ic_launcher).into(settingIcon03);
        }
    };*/

    private void initTitle()
    {
        mainToolBar.setTitle("");
        barTitle.setText("天气预报");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        mainToolBar.setNavigationIcon(null);
    }

    private void initTouch()
    {
        //2、设置ItemTouchHelper
        ItemTouchHelper.Callback callback = new MyItemTouchHelperCallback(adapter);
        mItemTouchHelper = new ItemTouchHelper(callback);
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);
    }

    private void initRecyclerView()
    {
        mRecyclerView = pullLoadMoreRecyclerView.getRecyclerView();
        mRecyclerView.addItemDecoration(new RecycleViewDividerForList(
                MainActivity.this, LinearLayoutManager.HORIZONTAL));
        datas = new ArrayList<MainBean.MainSub>();
        //这里用线性显示 类似于listview
        adapter = new MainRecyclerViewAdapter(MainActivity.this, datas);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        //显示下拉刷新
        pullLoadMoreRecyclerView.setRefreshing(true);
        //设置上拉刷新文字
        pullLoadMoreRecyclerView.setFooterViewBackgroundColor(android.R.color.transparent);
        //设置上拉刷新文字颜色
        //mPullLoadMoreRecyclerView.setFooterViewTextColor(R.color.white);
        //设置加载更多背景色
        //mPullLoadMoreRecyclerView.setFooterViewBackgroundColor(R.color.colorBackground);
        pullLoadMoreRecyclerView.setLinearLayout();

        pullLoadMoreRecyclerView.setOnPullLoadMoreListener(this);
        pullLoadMoreRecyclerView.setAdapter(adapter);
        pullLoadMoreRecyclerView.refresh();
        adapter.setmOnItemClickListener(new MainRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(!pullLoadMoreRecyclerView.isRefresh()&&null!=datas&&!datas.isEmpty()&&null!=datas.get(position))
                {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", datas.get(position));
                    showActivity(MainActivity.this, DetailActivity.class, bundle);
                }
            }
        });
    }

    Runnable runnableReflush = new Runnable() {
        @Override
        public void run() {
            if(null!=mainCall)
            {
                final Call<MainBean> callReflush = mainCall.clone();
                callReflush.enqueue(new Callback<MainBean>() {
                    @Override
                    public void onResponse(Call<MainBean> call, Response<MainBean> response) {
                        callReflush.cancel();
                        List<MainBean.MainSub> results = response.body().result;
                        if(null!=results&&!results.isEmpty())
                        {
                            datas.clear();
                            datas.addAll(results);
                            adapter.notifyDataSetChanged();
                            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        }
                        else
                        {
                            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        }
                    }

                    @Override
                    public void onFailure(Call<MainBean> call, Throwable t) {
                        callReflush.cancel();
                        pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };

    Runnable runnableLoadMore = new Runnable() {
        @Override
        public void run() {
            if(null!=mainCall)
            {
                final Call<MainBean> callLoadMore = mainCall.clone();
                callLoadMore.enqueue(new Callback<MainBean>() {
                    @Override
                    public void onResponse(Call<MainBean> call, Response<MainBean> response) {
                        callLoadMore.cancel();
                        List<MainBean.MainSub> results = response.body().result;
                        if(null!=results&&!results.isEmpty())
                        {
                            datas.addAll(results);
                            adapter.notifyDataSetChanged();
                            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        }
                        else
                        {
                            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        }
                    }

                    @Override
                    public void onFailure(Call<MainBean> call, Throwable t) {
                        callLoadMore.cancel();
                        pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        Toast.makeText(MainActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=pullLoadMoreRecyclerView)
        {
            pullLoadMoreRecyclerView.cancelLongPress();
        }
        if(null!=mainCall)
        {
            mainCall.cancel();
        }
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableReflush);
            mHandler.removeCallbacks(runnableLoadMore);
            /*mHandler.removeCallbacks(runnableLoadMenu);*/
        }
        ButterKnife.unbind(this);
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(runnableReflush, 1000);
    }

    @Override
    public void onLoadMore() {
        mHandler.postDelayed(runnableLoadMore, 1000);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        /*if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            if(null!=menu&&menu.isMenuShowing())
            {
                menu.toggle();
            }
            else if(null!=menu&&!menu.isMenuShowing())
            {
                if ((System.currentTimeMillis() - exitTime) > 2000)
                {
                    Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_LONG).show();
                    exitTime = System.currentTimeMillis();
                } else
                {
                    closeSelf(MainActivity.this);
                    killAppDestory(MainActivity.this);
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);*/
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            closeSelf(MainActivity.this);
        }
        return super.onKeyDown(keyCode, event);
    }
}
